<?php

defined('BASEPATH') OR exit('No direct script access allowed');

/**
 * 组织机构管理
 * @exception 400 参数错误
 * @exception 502 服务器错误
 * @exception 503 数据库错误
 */
class DepartmentController extends CI_Controller
{
    public function __construct()
    {
        parent::__construct();
        $this->load->library('Request');
        $this->load->model('Department');
    }


    /**
     * @return array
     */
    static function getRules()
    {
        return [
            'deptTree' => [
                'pid' => [
                    'name' => 'pid', 'type' => 'int', 'require' => false, 'default' => 0, 'desc' => '父级id', 'source' => 'get'
                ]
            ],
            'addDept' => [
                'name' => [
                    'name' => 'name', 'type' => 'string', 'max' => 20, 'require' => true, 'desc' => '名称(20字符内)', 'source' => 'post'
                ],
                'pid' => [
                    'name' => 'pid', 'type' => 'int', 'require' => false, 'default' => 0, 'desc' => '父级id(没有则不传或传0)', 'source' => 'post'
                ],
                'sort' => [
                    'name' => 'sort', 'type' => 'int', 'require' => false, 'default' => 0, 'desc' => '排序值(越小越靠前)', 'source' => 'post'
                ],


            ],
            'getDept' => [
                'id' => [
                    'name' => 'id', 'type' => 'int', 'require' => true, 'desc' => '组织机构id', 'source' => 'get'
                ]
            ],
            'modDept' => [
                'id' => [
                    'name' => 'id', 'type' => 'int', 'require' => true, 'desc' => '组织机构id', 'source' => 'post'
                ],
                'name' => [
                    'name' => 'name', 'type' => 'string', 'max' => 20, 'require' => false, 'desc' => '名称(20字符内)', 'source' => 'post'
                ],
                'pid' => [
                    'name' => 'pid', 'type' => 'int', 'require' => false, 'default' => 0, 'desc' => '父级id(没有则不传或传0)', 'source' => 'post'
                ],
                'sort' => [
                    'name' => 'sort', 'type' => 'int', 'require' => false, 'default' => 0, 'desc' => '排序值(越小越靠前)', 'source' => 'post'
                ],


            ],
        ];
    }


    /**
     * 组织机构
     * @desc 获取组织结构树(启用的)
     */
    public function deptTree()
    {
        $data = $this->request->getData(); // 获取参数
        $result = $this->department->getDeptTree();

        restful(200, $result);
    }


    /**
     * 组织机构
     * @desc 获取组织结构信息
     * @return int id 组织机构id
     * @return string name 组织机构名称
     * @return int parentId 父级id
     * @return int sort 排序值
     * @return int status 状态值（0正常 1禁用）
     * @throws MyException
     */
    public function getDept()
    {
        $data = $this->request->getData();
        $department = $this->db->select('id, name, parentId, sort')->where('id', $data['id'])->get('department')->row_array();
        restful(200, $department);
    }


    /**
     * 组织机构
     * @desc 添加
     * @throws MyException
     */
    public function addDept()
    {
        $data = $this->request->getData();
        $data['parentId'] = $data['pid'];
        unset($data['pid']);
		//是否可添加此部门 的子部门
		if($data['parentId'] > 0 && !$this->auth->checkRights([$data['parentId']],Auth::DEPT))
			throw new MyException('',MyException::NO_RIGHTS);
        $result = $this->department->add($data);
        if ($result !== false) {
            $this->optlog->write($result,'添加部门'.$data['name'],optlog::ADDDEPT);
            restful(201, '操作成功');
        }else throw new MyException('', MyException::DATABASE);
    }


    /**
     * 组织机构
     * @desc 修改
     * @throws MyException
     */
    public function modDept()
    {
        $data = $this->request->getData();
        $data['parentId'] = $data['pid'];
        unset($data['pid']);

		if (!$this->auth->checkRights([$data['id']],Auth::DEPT)){
            throw new MyException('',MyException::NO_RIGHTS);
        }
        $result = $this->department->mod($data);


        if ($result !== false) {
            $this->optlog->write($data['id'],'修改部门'.($data['name']?? ''),optlog::MODDEPT);
            restful(200, '操作成功');
        }else throw new MyException('', MyException::DATABASE);
    }

    /**
     * 组织机构
     * @desc 删除部门
     * @throws MyException
     */
    public function delDept(int $id=0)
    {
        $data = ['id'=>$id];
		if (!$this->auth->checkRights([$data['id']],Auth::DEPT)){
            throw new MyException('',MyException::NO_RIGHTS);
        }
        //获取当前部门ID的下级部门,如果不为空，则不能删除
        $num=$this->db->where('parentId',$id)->count_all_results('department');
        if($num>0){
            throw new MyException('组织包含下属组织，不能删除',MyException::INPUT_ERR);
        }
        $info = $this->department->deptNameByID([$data['id']]);
        $result = $this->department->delete($data['id']);
        if ($result !== false) {
            //日志
            $this->optlog->write($data['id'],'删除部门'.$info,optlog::DELDEPT);
            restful();
        }else throw new MyException('', MyException::DATABASE);
    }
}
